/**
 * 自定义plugin，通过 html-webpack-plugin 的钩子，修改js和css引入，添加hash；
 * */

const HtmlWebpackPlugin = require('html-webpack-plugin')
const htmlAutoprefixer = require('html-autoprefixer')
const { setSrcHash } = require('./util.js')

class MyHtmlPlugin {
  constructor(options) {
    this.options = options
    // console.log(options);
  }

  apply(compiler) {
    let This = this

    compiler.hooks.compilation.tap('MyHtmlPlugin', (compilation) => {
      HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync('MyHtmlPlugin', (htmlPluginData, callback) => {
        let filename = this.options.filePath.replace(this.options.srcPath + '\\', '')

        if (filename === htmlPluginData.plugin.options.filename) {
          let hash = compilation.hash.substring(0, 8);

          // 为引入的 css 和 script 添加hash
          // htmlPluginData.html = htmlPluginData.html.replace(/(<link\b[^>]*href=["'][^>]+)(\.css["'][^>]*>)/igm, '$1.' + hash + '$2')
          // htmlPluginData.html = htmlPluginData.html.replace(/(<script\b[^>]*src=["'][^>]+)(\.js["'][^>]*><\/script>)/igm, '$1.' + hash + '$2')
          // htmlPluginData.html = htmlAutoprefixer.process(htmlPluginData.html, { lowerCaseTags: false })


          htmlPluginData.html = setSrcHash(htmlPluginData.html, This.options, hash)

        }

        callback(null, htmlPluginData)
      })
    })
  }
}

module.exports = MyHtmlPlugin;
